var fs = require("fs");
var jsonFormat = require("json-format");
var crypto = require('crypto');

var StorageAdapter = function (filePath) {
    this.filePath = filePath;
};

StorageAdapter.prototype.writeFile = function (fileData) {
    if(this.md5 != crypto.createHash('md5').update(fileData).digest("hex")){
        let fd = fs.openSync(this.filePath, "w");
        fs.ftruncateSync(fd);
        fs.writeSync(fd, fileData);
        fs.closeSync(fd);
    }
};

StorageAdapter.prototype.read = function () {
    let data = {};
    try {
        let fd = fs.openSync(this.filePath, "r");
        let fileContent = fs.readFileSync(fd, "utf-8");
        data = JSON.parse(fileContent); 
        if(data != null){
            this.md5 = crypto.createHash('md5').update(fileContent).digest("hex");
        }
        fs.closeSync(fd);
    } catch (err) {
        console.log(err);
    }
    return data;
};

StorageAdapter.prototype.write = function (data) {
    let config = {
        type: "space",
        size: 2,
    };
    try {
        this.writeFile(jsonFormat(data, config));
    } catch (err) {
        this.writeFile(JSON.stringify(data));
    }
};

module.exports = StorageAdapter;
